package com.superc.notebook;

import java.util.ArrayList;
import java.util.Calendar;

import android.app.KeyguardManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;

import com.superc.lib.helper.AndroidHelper;
import com.superc.lib.intent.IntentFunction;
import com.superc.lib.intent.MulitSelector;
import com.superc.model.notebook.NotebookDBHelper;
import com.superc.model.notebook.NotebookDBHelper.NightModelType;
import com.superc.model.notebook.NotebookItem;

public class NotebookService extends Service implements Runnable {
    
	private NotebookBind binder=new NotebookBind();
	private boolean isStopAlert=false;
	private Thread alertThread =null;
	private NotebookDBHelper helper=null;
	private static NotebookBind laterBinder=null;
	private Context my=null;

	private static ServiceConnection mServiceConnection = new ServiceConnection() {  
        
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			laterBinder=(NotebookBind)service;
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
		}  
    };
    
    public static NotebookService getRunningService(){
    	if(laterBinder!=null){
    		return laterBinder.getService();
    	}return null;
    }
    
    public  static void startService(Context my,boolean bind){
    	Intent serviceIntent=IntentFunction.getDirectIntent(my, NotebookService.class);
		my.startService(serviceIntent);
		if(bind){
			bindService(my);
		}
    }
    
    public void startMonitorThread(boolean bolStart){
    	if(bolStart){
    		if(alertThread==null){
	    		alertThread=new Thread(this);
	    		alertThread.start();
    		}
    		else{
    			if(!alertThread.isAlive()){
    				alertThread.start();
    			}
    		}
    	}
    }
    
    public static NotebookService bindService(Context my){
    	try{
	    	Intent serviceIntent=IntentFunction.getDirectIntent(my, NotebookService.class);
	    	my.bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);  
	    	return getRunningService();
    	}
    	catch(Exception e){
    		e.printStackTrace();
    	}
    	return null;
    }
    
    public  static void stopService(Context my){
    	Intent serviceIntent=IntentFunction.getDirectIntent(my, NotebookService.class);
		my.stopService(serviceIntent);
    }
    
    
	@Override
	public IBinder onBind(Intent intent) {
		return binder;
	}

	@Override
	public void onCreate() {
		my=this;
		NotebookDBHelper.loadConfig(my);
		super.onCreate();
		startMonitorThread(true);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}

	@Override
	public boolean onUnbind(Intent intent) {
		return super.onUnbind(intent);
	}

	
	@Override
	public void run() {
		boolean isDisableKeyguard=false;
		KeyguardManager km=null;
		KeyguardManager.KeyguardLock mKeyguardLock=null;
		helper=new NotebookDBHelper(this);
		while(!isStopAlert){
			isDisableKeyguard=false;
			NotebookItem item=helper.getNextNearestAlertItem();
			try {
				if(item==null||item.getNextRuntimeInMillis()==0) {
					Thread.sleep(30000);
				}
				else{
					Calendar currentTime=Calendar.getInstance();
					long sleepTime=item.getNextRuntimeInMillis()-currentTime.getTimeInMillis();
					Thread.sleep(sleepTime);
					ArrayList<NotebookItem> results=helper.updateExpireItem(NotebookDBHelper.getNightAlertType()==NightModelType.NightModel_Contiute);
					if(results.size()>0){
						km = (KeyguardManager) my.getSystemService(Context.KEYGUARD_SERVICE);  
						mKeyguardLock = km.newKeyguardLock(this.toString());  
						if (km.inKeyguardRestrictedInputMode()) {  
							mKeyguardLock.disableKeyguard();
							isDisableKeyguard=true;
						}
						if(NotebookDBHelper.getNightAlertType()==NightModelType.NightModel_Ignore||
								(currentTime.get(Calendar.HOUR_OF_DAY)<=NotebookDBHelper.getNightEndHour() && 
								 currentTime.get(Calendar.HOUR_OF_DAY)>=NotebookDBHelper.getNightStartHour())  ){
							switch(item.getAlertType()){
								case NotebookConfig.AlertType_Shock:{
									AndroidHelper.ShowShock(my,NotebookDBHelper.getShockDelay()*1000);
									break;
								}
								case NotebookConfig.AlertType_Sound:{
									AndroidHelper.PlayMusic(my, NotebookDBHelper.getSongFilePath());
									break;
								}
							}
						}
						if(NotebookDBHelper.getNightAlertType()!=NightModelType.NightModel_Contiute){
							Intent alertIntent=IntentFunction.getDirectIntent(my, NotebookItemAlert.class);
							alertIntent.putExtra(MulitSelector.BUNDEL_NAME, results);
							alertIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK+Intent.FLAG_ACTIVITY_MULTIPLE_TASK );
							startActivity(alertIntent);
						}
					}
				}
			} catch (InterruptedException e) {
				break;
			}
			finally{
				if(isDisableKeyguard){
					//mKeyguardLock.reenableKeyguard();
				}
			}
		}
	}
	
	public void StopThread(){
		if(alertThread!=null)
			alertThread.interrupt();
	}
	
	public class NotebookBind extends Binder{
		NotebookService getService(){
			return NotebookService.this;
		}
	}
    
}
